package com.translate.web.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池配置
 **/
@Configuration
public class ThreadPoolConfig {


    /**
 	* 最大可创建的线程数
 	**/
    private int maxPoolSize = 50;

    /**
 	* 队列最大长度
 	**/
    private int queueCapacity = 10000;

    /**
 	* 线程池维护线程所允许的空闲时间
 	**/
    private int keepAliveSeconds = 300;

    @Bean(name = "threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setMaxPoolSize(maxPoolSize);
        
        int cpuCoreNumber = Runtime.getRuntime().availableProcessors();
        
        executor.setCorePoolSize(cpuCoreNumber + 1);
        executor.setQueueCapacity(queueCapacity);
        executor.setKeepAliveSeconds(keepAliveSeconds);
        // 设置处理策略 优先处理策略（CallerRunsPolicy ）
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return executor;
    }

}

